﻿using System;
using System.Net;
using IPTools.Core;
using Microsoft.Extensions.DependencyInjection;

namespace net.xBei.Helper {
    /// <summary>
    /// 
    /// </summary>
    public static class IpAddressHelper {
        /// <summary>
        /// 从IP地址中获取地区信息
        /// </summary>
        /// <param name="iPAddress"></param>
        /// <returns></returns>
        public static string GetRegionByIpAddress(this IPAddress iPAddress)
            => iPAddress == null
                    ? string.Empty
                    : GetRegionByIpAddressString(iPAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6 ? iPAddress.MapToIPv4().ToString() : iPAddress.ToString());
        /// <summary>
        /// 从IP地址中获取地区信息
        /// </summary>
        /// <param name="ipstring"></param>
        /// <returns></returns>
        public static string GetRegionByIpAddress(string ipstring)
            => IPAddress.TryParse(ipstring, out var ip) ? GetRegionByIpAddress(ip) : string.Empty;
        static string GetRegionByIpAddressString(string ipstring) {
            try {
                var ipinfo = IpTool.Search(ipstring);
                if (ipinfo == null) {
                    return string.Empty;
                }
                if (ipinfo.Country != "中国" && IpTool.IpAllSearcher != null) {
                    ipinfo = IpTool.IpAllSearcher.SearchWithI18N(ipstring);
                    Console.WriteLine(ipinfo.ToJson(true));
                }
                return string.Format("{0}-{1}-{2}-{3}", ipinfo.Country, ipinfo.Province, ipinfo.City, ipinfo.NetworkOperator);
            } catch {
                return string.Empty;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="services"></param>
        /// <param name="ChinaDbPath"></param>
        /// <param name="InternationalDbPath"></param>
        /// <param name="useMemoryCache"></param>
        public static void SetupIpTools(this IServiceCollection services,
                                        string ChinaDbPath,
                                        string? InternationalDbPath = default,
                                        bool? useMemoryCache = true) {
            IpToolSettings.LoadInternationalDbToMemory = useMemoryCache == true;
            if (!string.IsNullOrWhiteSpace(ChinaDbPath)) {
                IpToolSettings.ChinaDbPath = ChinaDbPath;
            }
            if (!string.IsNullOrWhiteSpace(InternationalDbPath)) {
                IpToolSettings.InternationalDbPath = InternationalDbPath;
            }
        }
    }
}
